package com.bruce.codeFactory.Thread;

/**
 * @author luotuan
 * @Description  死锁的小型例子
 * @create 2019-02-19 21:18
 **/
public class DeadLockDemo {
    private final Object lock = new Object();
    private OtherService otherService;

    private DeadLockDemo(OtherService otherService) {
        this.otherService = otherService;
    }

    public void m1() {
        synchronized (lock) {
            System.out.println("m1==================");
            otherService.s1();
        }
    }

    public void m2() {
        synchronized (lock) {
            System.out.println("m2=====================");
        }
    }

    public static void main(String[] args) {
        OtherService otherService = new OtherService();
        DeadLockDemo deadLockDemo = new DeadLockDemo(otherService);
        otherService.setDeadLockDemo(deadLockDemo);
        new Thread(){
            @Override
            public void run() {
                while (true){
                    deadLockDemo.m1();
                }
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    otherService.s2();
                }
            }
        }.start();
    }
}

class OtherService {
    private final Object lock = new Object();
    private DeadLockDemo deadLockDemo;

    public void setDeadLockDemo(DeadLockDemo deadLockDemo) {
        this.deadLockDemo = deadLockDemo;
    }

    public void s1() {
        synchronized (lock) {
            System.out.println("s1==================");
        }
    }

    public void s2() {
        synchronized (lock) {
            System.out.println("s2==================");
            deadLockDemo.m2();
        }
    }
}
